import MSLogger
import MSDBTemplates
import MySQLdb
from time import sleep

def getDBConnection(DBHost, DBName, DBUser, DBPass, DBConnReestablishmentDelay=5, DBConnReestablishmentAttemptCount=3):
    attemptCount = 0
    conn = None
    while True:
        try:    
            conn = MySQLdb.connect(DBHost, DBUser, DBPass, DBName)
            break
        except:
            secs = DBConnReestablishmentDelay
            attemptCount += 1
            if attemptCount > DBConnReestablishmentAttemptCount:
                attemptCount = 0
                secs *= 10
            MSLogger.logWarn('PCN connect failed: sleep %d secs before new attempt' % (secs))
            sleep(secs)
	    continue
    return conn

def checkDBConnection(oldConn, DBHost, DBName, DBUser, DBPass):
    if oldConn == None:
        MSLogger.logDebug('setting up new connection to PCN DB')
        oldConn = getDBConnection(DBHost, DBName, DBUser, DBPass)
    if oldConn.errno() != 0:
        MSLogger.logDebug('reestablish connection to PCN DB')
        oldConn = getDBConnection(DBHost, DBName, DBUser, DBPass)
    return oldConn

def storeStaticEvents(Events, DBConnection, DBHost, DBName, DBUser, DBPass):
    if Events == None or len(Events)==0:
        return DBConnection
    try:
        DBConnection = checkDBConnection(DBConnection, DBHost, DBName, DBUser, DBPass)
        DBCursor = None
        DBCursor = DBConnection.cursor()
        recId = MSDBTemplates.get_FromSGN_LastRecId(DBCursor)
        Events.sort()
        for e in Events:
            e.userWriterId = str(DBUser)
            recId = MSDBTemplates.store_MSEvent_ToSGN(e, DBCursor, recId)
        DBConnection.commit()
    except (Exception), err:
        MSLogger.logError('failed to store events with exception: %s' % str(err))
    return DBConnection

def storeMobileEvents(Events, DBConnection, DBHost, DBName, DBUser, DBPass):
    if Events == None or len(Events)==0:
        return DBConnection
    try:
        DBConnection = checkDBConnection(DBConnection, DBHost, DBName, DBUser, DBPass)
        DBCursor = None
        DBCursor = DBConnection.cursor()
        recId = MSDBTemplates.get_FromRecords_LastRecId(DBCursor)
        Events.sort()
        MSDBTemplates.store_MSEvent_ToObj(Events[len(Events)-1], DBCursor)
        for e in Events:
            recId = MSDBTemplates.store_MSEvent_ToRecords(e, DBCursor, recId)
        DBConnection.commit()
    except (Exception), err:
        MSLogger.logError('failed to store events with exception: %s' % str(err))
    return DBConnection
